const QQMapWX = require('../../utils/qqmap-wx-jssdk.min');
const { HTTP } = require('../../utils/http');
const { api } = require('../../utils/api');
const { request } = new HTTP();
let qqmapsdk = null;
const app = getApp();
Page({
  data: {
    text: '',
    latitude: '',
    longitude: '',
    currentValue: ''
  },
  onLoad(options) {
    const { value = '' } = options;
    this.setData({
      currentValue: value ? decodeURIComponent(value) : ''
    });
    qqmapsdk = new QQMapWX({
      key: '3HLBZ-DACKD-YRP4I-HZE6V-KVSPV-P6FGR'
    });
  },
  onShow() {
    const self = this;
    if (!this.data.currentValue) {
      wx.getLocation({
        type: 'gcj02',
        success(res) {
          const latitude = res.latitude;
          const longitude = res.longitude;
          qqmapsdk.reverseGeocoder({
            location: {
              longitude,
              latitude
            },
            success: function(res) {
              const text = res.result.address_component.city  + ' ' + res.result.address_component.district;
              self.setData({
                text,
                longitude,
                latitude
              });
              
            }
          });
        }
      })
    }
   
  },
  sure() {
    const params = {
      position: this.data.text,
      latitude: this.data.latitude,
      longitude: this.data.longitude
    };
    this._edit(params);
  },
  async _edit(params) {
    const {returnCode = '', bean = {}} = await request({
      url: api.editUser,
      method: 'put',
      data: params
    });
    if (returnCode === '0000') {
      wx.showToast({ title: '资料修改成功', icon: 'none', duration: 2000 });
      wx.navigateBack({
        delta: 1
      });
    }
  }

});